package handler

import (
	"github.com/gin-gonic/gin"
	jwt "github.com/golangblogs/gojwt"
	"net/http"
	"time"
	"zk/zg3_zk1/src/pro/global"
	"zk/zg3_zk1/src/pro/internal/model"
	"zk/zg3_zk1/src/pro/internal/params"
)

func Login(c *gin.Context) {
	var err error
	var req params.LoginReq
	var u model.User

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	}
	if err = u.GetUserByMobile(req.Mobile); err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code":    404,
			"message": "该账号不存在",
		})
		return
	}
	if u.Password != req.Password {
		c.JSON(http.StatusNotFound, gin.H{
			"message": "密码错误",
		})
		return
	}

	newJwt := jwt.NewJWT("Token")
	claims := jwt.CustomClaims{
		ID: u.ID,
	}

	token, _ := newJwt.CreateToken(claims)

	global.Rdb.Set(global.Ctx, "Token"+u.Mobile, token, time.Hour*5)

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "用户登录成功",
		"data":    token,
	})
}

func FriendsList(c *gin.Context) {
	var err error
	var req params.FriendListReq
	var uf model.UserFollow

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	}
	if err = uf.GetUfByUserId(req.UserId); err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code":    404,
			"message": "查询失败",
		})
		return
	}

	global.Rdb.Set(global.Ctx, "UserId"+uf.DistNickName, uf, time.Hour)

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "查询成功",
		"data": gin.H{
			"dist_id":        uf.DistId,
			"dist_nick_name": uf.DistNickName,
		},
	})
}
